package cn.tedu.dao;

import cn.tedu.entity.Book;
import cn.tedu.utils.DBUtils;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author JokerQiu
 * @date 2021年12月16日 15:53
 */

public class BookDao {
    /**
     * 获取书籍列表
     *
     * @return
     * @throws SQLException
     */
    public List<Book> getBookList() throws SQLException {
        //获取连接
        Connection connection = DBUtils.getConnection();
        Statement statement = connection.createStatement();
        String sql = "select * from t_book";
        ResultSet resultSet = statement.executeQuery(sql);
        // 处理结果集
        List<Book> bookList = new ArrayList<>();
        while (resultSet.next()) {
            Book book = new Book();
            book.setAuthor(resultSet.getString("author"));
            book.setAuthorSummary(resultSet.getString("author_summary"));
            book.setDangPrice(resultSet.getDouble("dang_price"));
            book.setDescription(resultSet.getString("description"));
            book.setFixedPrice(resultSet.getDouble("fixed_price"));
            book.setId(resultSet.getInt("id"));
            book.setProductName(resultSet.getString("product_name"));
            book.setProductPic(resultSet.getString("product_pic"));
            book.setPublishing(resultSet.getString("publishing"));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String publishTime = resultSet.getString("publish_time");
            Long publishTimeLong = Long.parseLong(publishTime);
            Date date = new Date(publishTimeLong);
            String dateString = format.format(date);
            book.setPublishTime(dateString);
            book.setScore(resultSet.getInt("score"));
            bookList.add(book);
        }
        // 关闭资源
        DBUtils.close(resultSet, statement, connection);
        return bookList;
    }

    /**
     * 根据id获取书籍
     *
     * @param bookId 书籍id
     * @return 书籍信息
     * @throws SQLException
     */
    public Book getBookById(String bookId) throws SQLException {
        Connection connection = DBUtils.getConnection();
        String sql = "SELECT id,product_name,fixed_price,dang_price FROM t_book WHERE id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, bookId);
        ResultSet resultSet = statement.executeQuery();
        Book book = new Book();
        while (resultSet.next()) {
            book.setId(resultSet.getInt("id"));
            book.setProductName(resultSet.getString("product_name"));
            book.setDangPrice(resultSet.getDouble("dang_price"));
            book.setFixedPrice(resultSet.getDouble("fixed_price"));
        }
        DBUtils.close(resultSet, statement, connection);
        return book;
    }
}
